export default function (context) {
  const {
    app,
    store,
    route,
    redirect,
    from
  } = context;

  //登录后需要才创建链接
  if (store.getters.isAuthenticated && !window.PAGE_SOCKET) {
    try {
      let socket_active = false;
      let uuid = 'websocket';
      let tcp_uid = store.state.user.tcp_uid;
      let socket_url = store.state.user.websocket;
      if (!socket_url) {
        console.log('socket url error')
        return false;
      }
      let socket_ping_handle;
      window.PAGE_SOCKET = new WebSocket(socket_url);
      // Connection opened
      PAGE_SOCKET.addEventListener('open', function (event) {
        PAGE_SOCKET.send(JSON.stringify({
          "action": 100001,
          "user_id": tcp_uid,
          "token": store.state.token,
          "dateline": parseInt(+new Date / 1000),
          "data": {},
          "uuid": uuid
        }));
        ping();
      });

      PAGE_SOCKET.addEventListener('message', function (event) {
        // socket_active = true;
        try {
          let data = JSON.parse(event.data);
          if (data.code == 0) {
            switch (data.action) {
              //扫码支付-要求付款人确认并输入支付密码
              case 200003:
                let route_info = {
                  name: 'pay-confirm',
                  query: {
                    id: data.data.order_id,
                    type: 'scan-pay',
                  },
                  params: {
                    data: {
                      ...data.data,
                      order_info: data.data.recver_info.name,
                      shop_id:data.data.recver_info.shop_id,
                    }
                  }
                }
                if (store.name == 'pay-confirm') {
                  app.router.replace(route_info)
                } else {
                  app.router.push(route_info)
                }
                break;
            }

          } else if (data.code == -100) { //登录被踢出
            close();
            //避免多次触发
            store.getters.isAuthenticated && app.$alert('您的账号已在其他设备进行登录').then(() => {
              app.router.push('/login');
            }).catch(e => {
              app.router.push('/login');
            })

            store.dispatch('LOGOUT')

          }
        } catch (e) {
          console.log(e);
        }

      });

      PAGE_SOCKET.addEventListener('close', function (e) {
        console.log(e)
      })

      PAGE_SOCKET.addEventListener('error', function (e) {
        console.log(e)
      })

      function close() {
        clearTimeout(socket_ping_handle);
        PAGE_SOCKET.close();
        window.PAGE_SOCKET = null;
      }

      //每10秒需要发送心跳包给客户端，不然客户端会中断请求,防止中断js端用8s
      function ping() {
        if (socket_ping_handle && !store.getters.isAuthenticated) {
          close();
          //退出登录后断开心跳包
          return false;
        }
        if (PAGE_SOCKET.readyState == 1) {
          PAGE_SOCKET.send(JSON.stringify({
            "action": 100002,
            "user_id": tcp_uid,
            "token": store.state.token,
            "dateline": parseInt(+new Date / 1000),
            "data": {},
            "uuid": uuid
          }));
          socket_ping_handle = setTimeout(ping, 8000);
        }
      }
    } catch (e) {
      console.log(e);
    }
  }
}
